from dto.user_model import User
from extensions import db  # 导入数据库实例

class UserService:
    """用户服务类，处理用户相关业务逻辑"""

    def save_user(self, user_data):
        """
        保存用户数据到数据库

        Args:
            user_data (dict): 包含name和email的用户数据

        Returns:
            User: 保存后的用户对象

        Raises:
            Exception: 如果保存失败抛出异常
        """
        try:
            new_user = User(style_id=user_data['style_id'], live=user_data['live'], update_by=user_data['update_by'])
            db.session.add(new_user)
            db.session.commit()
            return new_user
        except Exception as e:
            db.session.rollback()
            raise Exception(f"保存用户失败: {str(e)}")

    def get_users_by_style_and_live(self,style_id:int=None,live:bool=None,page=1,page_size=10) -> list:
        """根据 style_id 和 live 查询用户"""
        try:
            query = User.query
            if style_id:
                query = query.filter_by(style_id=style_id)
            if live is not None:
                query = query.filter_by(live=live)
            pagination = query.paginate(
                page=page,
                per_page=page_size,
                error_out=False
            )
            users = pagination.items
            total = pagination.total
            return users,total
        except Exception as e:
            raise Exception(f"查询失败：{str(e)}")